import { asyncRoutes, constantRoutes } from '@/router'
import store from '@/store'
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some(role => route.meta.roles.includes(role))
//   } else {
//     return true
//   }
// }


/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, permissions) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    // if (hasPermission(roles, tmp)) {
    if (newCheck(tmp, permissions)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, permissions)
      }
      res.push(tmp)
    }
  })

  return res
}
// 根据后台权限解析route
function newCheck(tmp, permissions) {
  // var allowed = ['Permission', 'Orderlist', 'userOrder']
  // console.log(tmp.name)
  if (tmp.name === undefined) {
    return false
  }
  return permissions.includes(tmp.name)
}

const state = {
  routes: [],
  addRoutes: [],
  hasDashboard: false
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_DASHBOSRD: (state, hasDashboard) => {
    state.hasDashboard = hasDashboard
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(async resolve => {
      let accessedRoutes
      if (roles.includes('-super')) {
      // if (roles.includes('super')) {
        accessedRoutes = asyncRoutes || []
      } else {
        // 获取当前用户的权限菜单
        const permissions = await store.dispatch('user/getPers')
        if (permissions.includes('selectPhone')) {
          sessionStorage.setItem('selectPhone', 1)
        } else {
          sessionStorage.setItem('selectPhone', 0)
        }
        accessedRoutes = filterAsyncRoutes(asyncRoutes, permissions)
      }
      var hasDashboard = false
      if (accessedRoutes[0].name === 'Dashboard') {
        hasDashboard = true
        accessedRoutes = accessedRoutes.slice(1, accessedRoutes.length)
        commit('SET_ROUTES', accessedRoutes)
        commit('SET_DASHBOSRD', hasDashboard)
        resolve(accessedRoutes)
      } else {
        commit('SET_ROUTES', accessedRoutes)
        commit('SET_DASHBOSRD', hasDashboard)
        resolve(accessedRoutes)
      }
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
